package com.lxw.oa.schedule;

import com.lxw.oa.constant.ScheduleConstants;
import com.lxw.oa.entity.SysJob;
import com.lxw.oa.entity.SysJobLog;
import com.lxw.oa.service.SysJobLogService;
import com.lxw.oa.util.StringUtil;
import com.lxw.oa.util.scheduleUtil.BeanUtils;
import com.lxw.oa.util.scheduleUtil.SpringContextUtil;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 定时任务处理
 *
 * @author ruoyi
 *
 */
//禁止并发执行多个相同定义的JobDetail
@DisallowConcurrentExecution
public class ScheduleJob extends QuartzJobBean
{
   // private static final Logger log = LoggerFactory.getLogger(ScheduleJob.class);
   //Java通过Executors提供四种线程池，分别为：
  //  newCachedThreadPool创建一个可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程，若无可回收，则新建线程。
  //  newFixedThreadPool 创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待。
  //  newScheduledThreadPool 创建一个定长线程池，支持定时及周期性任务执行。
   // newSingleThreadExecutor 创建一个单线程化的线程池，它只会用唯一的工作线程来执行任务，
    // 保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

    private ExecutorService service = Executors.newSingleThreadExecutor();

    private final static SysJobLogService jobLogService = (SysJobLogService) SpringContextUtil.getBean("sysJobLogService");

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException
    {
        SysJob job = new SysJob();
        BeanUtils.copyBeanProp(job, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES));

        SysJobLog jobLog = new SysJobLog();
        jobLog.setJobName(job.getJobName());
        jobLog.setJobGroup(job.getJobGroup());
        jobLog.setMethodName(job.getMethodName());
        jobLog.setMethodParams(job.getMethodParams());
        //jobLog.setCreateTime(new Date());

        long startTime = System.currentTimeMillis();

        try
        {
            // 执行任务
          //  log.info("任务开始执行 - 名称：{} 方法：{}", job.getJobName(), job.getMethodName());
            ScheduleRunnable task = new ScheduleRunnable(job.getJobName(), job.getMethodName(), job.getMethodParams());
            service.submit(task);
            //Future<?> future = service.submit(task);
            //future.get();
            long times = System.currentTimeMillis() - startTime;
            // 任务状态 0：成功 1：失败
            jobLog.setStatus("0");
            jobLog.setJobMessage(job.getJobName() + " 总共耗时：" + times + "毫秒");

          //  log.info("任务执行结束 - 名称：{} 耗时：{} 毫秒", job.getJobName(), times);
        }
        catch (Exception e)
        {
            e.printStackTrace();
           // log.info("任务执行失败 - 名称：{} 方法：{}", job.getJobName(), job.getMethodName());
          //  log.error("任务执行异常  - ：", e);
            long times = System.currentTimeMillis() - startTime;
            jobLog.setJobMessage(job.getJobName() + " 总共耗时：" + times + "毫秒");
            // 任务状态 0：成功 1：失败
            jobLog.setStatus("1");
            jobLog.setExceptionInfo(StringUtil.substring(e.getMessage(), 0, 4000));
        }
        finally
        {
            jobLogService.addJobLog(jobLog);
        }
    }
}
